<script setup>
import { ref } from 'vue'
import { useRouter, RouterLink } from 'vue-router'
import { saveAuth } from '../utils/tools/auth.js'
import { generateUniqueUserId } from '../utils/tools/idGenerator.js'
import { registerApi } from '@/api/user.js'
import AgreementModal from '../components/AgreementModal.vue'
import PrivacyModal from '../components/PrivacyModal.vue'

const router = useRouter()

const userId = ref('')
const username = ref('')
const password = ref('')
const confirm = ref('')
const loading = ref(false)
const errorMessage = ref('')
const agreeToTerms = ref(false)
const showAgreementModal = ref(false)
const showPrivacyModal = ref(false)

// 组件挂载时生成用户ID
userId.value = generateUniqueUserId()

// 清除错误信息
function clearError() {
  if (errorMessage.value) {
    errorMessage.value = ''
  }
}

function validate() {
  if (!username.value.trim()) return '请输入用户名'
  if (!password.value) return '请输入密码'
  if (password.value.length < 6) return '密码至少 6 位'
  if (password.value !== confirm.value) return '两次输入的密码不一致'
  if (!agreeToTerms.value) return '请先勾选用户协议'
  return ''
}

async function onSubmit() {
  errorMessage.value = ''
  const err = validate()
  if (err) { errorMessage.value = err; return }
  loading.value = true
  try {
    // 调用后端注册API
    const response = await registerApi(
      userId.value.trim(),
      username.value.trim(),
      password.value,
      3 // 默认权限为3，可以根据需要调整
    )
    
    if (response.code === 200) {
      // 注册成功，保存用户信息
      const user = {
        user_id: response.data.user_id,
        username: response.data.user_name,
        user_jurisdiction: response.data.user_jurisdiction
      }
      saveAuth(user)
      router.replace('/home')
    } else {
      // 注册失败，显示错误信息
      errorMessage.value = response.message || '注册失败'
    }
  } catch (e) {
    console.error('注册错误:', e)
    console.log('错误状态码:', e.status)
    console.log('错误消息:', e.message)
    
    // 处理不同类型的错误
    if (e.status === 401) {
      errorMessage.value = '缺少必要参数'
    } else if (e.status === 402) {
      errorMessage.value = '用户ID已存在'
    } else if (e.status === 403) {
      errorMessage.value = '用户名已存在'
    } else if (e.status === 500) {
      errorMessage.value = '服务器内部错误，请稍后重试'
    } else if (e.message.includes('Failed to fetch') || e.message.includes('NetworkError')) {
      errorMessage.value = '无法连接到服务器，请检查网络连接'
    } else if (e.message.includes('Request failed 401')) {
      errorMessage.value = '缺少必要参数'
    } else if (e.message.includes('Request failed 402')) {
      errorMessage.value = '用户ID已存在'
    } else if (e.message.includes('Request failed 403')) {
      errorMessage.value = '用户名已存在'
    } else if (e.message.includes('Request failed 500')) {
      errorMessage.value = '服务器内部错误，请稍后重试'
    } else {
      errorMessage.value = e.message || '注册失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

function showAgreement() {
  showAgreementModal.value = true
}

function showPrivacy() {
  showPrivacyModal.value = true
}

function closeAgreementModal() {
  showAgreementModal.value = false
}

function closePrivacyModal() {
  showPrivacyModal.value = false
}
</script>

<template>
  <div class="auth-container">
    <div class="split">
      <div class="panel form left" data-animate="slide-left">
        <div class="card">
          <div class="brand">
            <div class="logo">K</div>
            <div class="brand-text">
              <h2>KMS 注册</h2>
              <p class="subtitle">创建一个新账户以开始使用</p>
            </div>
          </div>
          <form @submit.prevent="onSubmit" class="form">
            <div class="socials">
              <button type="button" class="social google" aria-label="Google 注册">
                <svg viewBox="0 0 24 24"><path fill="currentColor" d="M21.35 11.1H12v2.9h5.35c-.23 1.48-1.61 4.34-5.35 4.34c-3.22 0-5.85-2.67-5.85-5.97S8.78 6.4 12 6.4c1.84 0 3.09.78 3.8 1.45l2.6-2.5C17.22 3.7 14.86 2.8 12 2.8C6.92 2.8 2.8 6.95 2.8 12s4.12 9.2 9.2 9.2c5.3 0 8.8-3.72 8.8-8.97c0-.6-.06-1.02-.15-1.13Z"/></svg>
                使用 Google 注册
              </button>
              <button type="button" class="social wechat" aria-label="微信注册">
                <svg viewBox="0 0 24 24"><path fill="currentColor" d="M9.5 5C5.91 5 3 7.24 3 10c0 1.5.84 2.86 2.18 3.79L4.5 16.5l2.98-.93c.62.17 1.28.26 2.02.26c3.59 0 6.5-2.24 6.5-4.99S13.09 5 9.5 5m-2 3a.75.75 0 1 1 0 1.5A.75.75 0 0 1 7.5 8m4 0a.75.75 0 1 1 0 1.5A.75.75 0 0 1 11.5 8M20 10.5c0 2.13-1.53 3.96-3.74 4.67c.09.31.15.64.15.98c0 .31-.05.61-.12.9L18.5 18l-2.1.7c-.43.12-.9.18-1.4.18c-2.93 0-5.3-1.78-5.55-4.04c.8.17 1.65.26 2.55.26C15.09 15.1 18 13.03 18 10.5c0-.69-.18-1.35-.5-1.95C19.2 8.95 20 9.65 20 10.5m-3.25-.75a.75.75 0 1 1 0 1.5a.75.75 0 0 1 0-1.5Z"/></svg>
                使用微信注册
              </button>
            </div>
            <div class="divider"><span>或</span></div>
            <label class="field">
              <span>用户ID</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
                <input v-model="userId" type="text" readonly placeholder="自动生成" class="user-id-input" />
              </div>
            </label>
            <label class="field">
              <span>用户名</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M12 12a5 5 0 1 0-5-5a5 5 0 0 0 5 5Zm0 2c-4.418 0-8 2.239-8 5v1h16v-1c0-2.761-3.582-5-8-5Z"/></svg>
                <input v-model="username" @input="clearError" type="text" placeholder="请输入用户名" autocomplete="username" />
              </div>
            </label>
            <label class="field">
              <span>密码</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M17 8h-1V6a4 4 0 1 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2Zm-6 0h2V6a2 2 0 1 0-4 0v2Zm6 10H7v-8h10v8Z"/></svg>
                <input v-model="password" @input="clearError" type="password" placeholder="请输入密码" autocomplete="new-password" />
              </div>
            </label>
            <label class="field">
              <span>确认密码</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M17 8h-1V6a4 4 0 1 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2Zm-6 0h2V6a2 2 0 1 0-4 0v2Zm6 10H7v-8h10v8Z"/></svg>
                <input v-model="confirm" @input="clearError" type="password" placeholder="请再次输入密码" autocomplete="new-password" />
              </div>
            </label>
            <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
            <div class="checkbox-container" style="margin-top: 6px;">
              <label class="checkbox">
                <input type="checkbox" v-model="agreeToTerms" />
                <span class="checkmark"></span>
              </label>
              <span class="checkbox-text">我已阅读并同意 <a class="link" href="javascript:void(0)" @click="showAgreement">用户协议</a> 和 <a class="link" href="javascript:void(0)" @click="showPrivacy">隐私政策</a></span>
            </div>
            <button class="primary" :disabled="loading">{{ loading ? '注册中...' : '注册并登录' }}</button>
          </form>
          <p class="switch">
            已有账号？<RouterLink to="/login">去登录</RouterLink>
          </p>
        </div>
      </div>
      <div class="panel image right" data-animate="slide-right">
        <div class="image-mask"></div>
      </div>
    </div>
    
    <!-- 弹窗组件 -->
    <AgreementModal 
      :show="showAgreementModal" 
      @close="closeAgreementModal"
      @agree="agreeToTerms = true"
    />
    <PrivacyModal 
      :show="showPrivacyModal" 
      @close="closePrivacyModal"
      @agree="agreeToTerms = true"
    />
  </div>
  
</template>

<style scoped>
.auth-container {
  min-height: 100dvh;
  display: grid;
  place-items: stretch;
  background:
    radial-gradient(1200px 600px at 10% -10%, rgba(16,185,129,.18), transparent 60%),
    radial-gradient(1000px 500px at 120% 10%, rgba(56,189,248,.18), transparent 60%),
    linear-gradient(135deg, #f8fafc 0%, #eef2f7 100%);
  overflow: hidden;
}
.split { width: 100%; height: 100dvh; display: grid; grid-template-columns: 1fr 1fr; gap: 0; padding: 0; }
.panel { border-radius: 0; overflow: hidden; position: relative; }
.panel.image { background: linear-gradient(135deg, #10b981, #22c55e); box-shadow: 0 20px 50px rgba(16,185,129,.22); }
.panel.form { background: transparent; display: grid; align-items: center; justify-items: center; padding: 40px; }
.image::before { content: ''; position: absolute; inset: 0; background: url('https://images.unsplash.com/photo-1552664730-d307ca884978?q=80&w=1640&auto=format&fit=crop') center/cover no-repeat; opacity: .9; filter: saturate(1.05); }
.image-mask { position: absolute; inset: 0; background:
  radial-gradient(420px 420px at 78% 22%, rgba(255,255,255,.28), transparent 60%),
  linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,0)); }
.card {
  width: 100%;
  max-width: 520px;
  background: rgba(255,255,255,0.85);
  backdrop-filter: blur(10px);
  border-radius: 18px;
  padding: 34px;
  box-shadow: 0 24px 60px rgba(15,23,42,0.18);
  border: 1px solid rgba(16,185,129,.18);
  animation: floatIn .3s ease-out;
}
.brand { display: flex; gap: 12px; align-items: center; margin-bottom: 14px; }
.logo { width: 40px; height: 40px; border-radius: 12px; background: linear-gradient(135deg, #10b981, #22c55e); color: #fff; display:grid; place-items:center; font-weight: 700; }
h2 { margin: 0 0 4px; font-size: 20px; }
.subtitle { margin: 0; color: #6b7280; font-size: 13px; }
.form { display: grid; gap: 14px; }
.field { display: grid; gap: 8px; }
.field span { color: #4b5563; font-size: 13px; font-weight: 600; letter-spacing: .2px; }
.input-wrapper { 
  position: relative; 
  border: 1px solid #e5e7eb; 
  border-radius: 14px; 
  background: linear-gradient(180deg, #ffffff, #f9fafb); 
  transition: border-color .2s, box-shadow .2s, background .2s, transform .1s; 
}
.input-wrapper:hover { 
  border-color: #d1d5db; 
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.input-wrapper:focus-within { 
  border-color: #10b981; 
  border-width: 2px;
  box-shadow: 
    0 0 0 3px rgba(16,185,129,.12),
    0 4px 16px rgba(16,185,129,.15),
    0 1px 3px rgba(0, 0, 0, 0.1);
  background: #fff; 
  transform: translateY(-1px);
}
.icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); width: 18px; height: 18px; color: #9ca3af; transition: color .2s; }
.input-wrapper:focus-within .icon { color: #10b981; }
.socials { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.social { display: grid; grid-auto-flow: column; align-items: center; justify-content: center; gap: 8px; border: 1px solid #e5e7eb; background: #fff; color: #111827; padding: 10px; border-radius: 12px; cursor: pointer; transition: box-shadow .2s, transform .05s, border-color .2s; }
.social svg { width: 18px; height: 18px; }
.social:hover { box-shadow: 0 8px 20px rgba(15,23,42,.08); border-color: #d1d5db; }
.social.google:hover { border-color: #93c5fd; }
.social.wechat:hover { border-color: #86efac; }
.divider { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; color: #9ca3af; font-size: 12px; margin: 6px 0 2px; }
.divider::before, .divider::after { content: ''; height: 1px; background: #e5e7eb; }
/* 复选框容器样式 */
.checkbox-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 自定义复选框样式 */
.checkbox { 
  display: inline-flex; 
  align-items: center; 
  cursor: pointer;
  position: relative;
  flex-shrink: 0;
}


.checkbox input { 
  position: absolute;
  opacity: 0;
  cursor: pointer;
  width: 0;
  height: 0;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  background: #fff;
  position: relative;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.checkbox:hover .checkmark {
  border-color: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.checkbox input:checked + .checkmark {
  background: linear-gradient(135deg, #10b981, #22c55e);
  border-color: #10b981;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.checkbox input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-text {
  user-select: none;
  transition: color 0.2s ease;
  color: #6b7280;
  font-size: 13px;
  font-weight: 500;
  line-height: 1.4;
}
.link { color: #10b981; font-size: 13px; text-decoration: none; }
.link:hover { text-decoration: underline; }
input { 
  appearance: none; 
  border: none; 
  background: transparent; 
  width: 100%; 
  border-radius: 14px; 
  padding: 12px 12px 12px 38px; 
  font-size: 14px; 
  color: #111827; 
  font-weight: 500;
  transition: color 0.2s ease;
}
input::placeholder { 
  color: #9ca3af; 
  font-weight: 400;
  transition: color 0.2s ease;
}
input:focus { 
  outline: none; 
  color: #0f172a;
  font-weight: 600;
}
input:focus::placeholder {
  color: #6b7280;
}
.primary {
  margin-top: 6px;
  background: #10b981;
  color: #fff;
  border: none;
  padding: 10px 14px;
  font-size: 14px;
  border-radius: 10px;
  cursor: pointer;
  transition: transform .05s ease, box-shadow .2s ease, background .2s ease;
  box-shadow: 0 6px 16px rgba(16,185,129,.35);
}
.primary:disabled { opacity: .7; cursor: not-allowed; box-shadow: none; }
.primary:active { transform: translateY(1px); }
.error { color: #ef4444; font-size: 13px; margin: 4px 0 0; }
.switch { margin-top: 14px; color: #6b7280; font-size: 14px; }

.panel[data-animate="slide-left"] { animation: slideInLeft .5s ease-out both; }
.panel[data-animate="slide-right"] { animation: slideInRight .5s ease-out both; }

@keyframes slideInLeft { from { opacity: 0; transform: translateX(-18px); } to { opacity: 1; transform: translateX(0); } }
@keyframes slideInRight { from { opacity: 0; transform: translateX(18px); } to { opacity: 1; transform: translateX(0); } }

@media (max-width: 900px) {
  .split { grid-template-columns: 1fr; height: auto; }
  .panel.image { order: 2; height: 220px; border-top-left-radius: 18px; border-top-right-radius: 18px; }
  .panel.form { order: 1; padding: 20px; }
}

@keyframes floatIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }

/* 用户ID输入框样式 */
.user-id-input {
  background-color: #f8f9fa !important;
  color: #6b7280 !important;
  cursor: not-allowed !important;
  border: 1px solid #e5e7eb !important;
  font-family: 'Courier New', monospace !important;
  font-weight: 600 !important;
  letter-spacing: 1px !important;
  pointer-events: none !important;
  user-select: none !important;
  width: 100% !important;
  max-width: 100% !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  padding-right: 8px !important;
}

.user-id-input:focus {
  outline: none !important;
  border-color: #e5e7eb !important;
  box-shadow: none !important;
  background-color: #f8f9fa !important;
  transform: none !important;
}

.user-id-input:hover {
  border-color: #e5e7eb !important;
  box-shadow: none !important;
  transform: none !important;
}

.user-id-input::placeholder {
  color: #9ca3af !important;
  font-style: italic !important;
}

/* 移除用户ID字段的包装器焦点效果 */
.field:has(.user-id-input) .input-wrapper {
  width: 100% !important;
  max-width: 100% !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
}

.field:has(.user-id-input) .input-wrapper:focus-within {
  border-color: #e5e7eb !important;
  box-shadow: none !important;
  transform: none !important;
  background: #f8f9fa !important;
  width: 100% !important;
  max-width: 100% !important;
}

.field:has(.user-id-input) .input-wrapper:hover {
  border-color: #e5e7eb !important;
  box-shadow: none !important;
  transform: none !important;
  background: #f8f9fa !important;
  width: 100% !important;
  max-width: 100% !important;
}
</style>


